//
//  GAOTabBar.swift
//  Weibo28
//
//  Created by 高辰 on 16/5/11.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit

class GAOTabBar: UITabBar {
    
    //composeButton的闭包
    var composeButtonClosure: (()->())?
    
    //懒加载撰写按钮
    private  lazy var composeButton: UIButton = {
        let button = UIButton()
        //背景图片
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: UIControlState.Normal)
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: UIControlState.Highlighted)
        //button的image
        button.setImage(UIImage(named: "tabbar_compose_icon_add"), forState: UIControlState.Normal)
        button.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: UIControlState.Highlighted)
        //设置button大小
        button.sizeToFit()
        //添加点击事件
        button.addTarget(self, action: "composeButtonAction", forControlEvents: UIControlEvents.TouchUpInside)
        
        return button
    }()
    
    
    override init(frame: CGRect) {
        
        super.init(frame: frame)
        
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func setupUI() {
        addSubview(composeButton)
    }
    
    //设置子控件位置
    override func layoutSubviews() {
        super.layoutSubviews()
        //撰写按钮位置
        composeButton.center.x = frame.size.width * 0.5
        composeButton.center.y = frame.size.height * 0.5
    
        //计算子控件大小及位置
        let itemWidth = bounds.size.width/5
        var index = 0
        
        for childView in subviews {
            if childView.isKindOfClass(NSClassFromString("UITabBarButton")!) {
                childView.bounds.size.width = itemWidth
                childView.frame.origin.x = CGFloat(index) * itemWidth
                index++
                if index == 2 {
                    index++
                }
                
            }
        }
    }
    
    
   @objc private func composeButtonAction() {
        
        composeButtonClosure?()
    }
    
    
    
    
}
